// 全局配置
const config = {
    apiBase: 'http://localhost/dev-api/system/wjh/list',
    imageBase: 'http://localhost:1024/dev-api/',
    pageSize: 10,
    currentPage: 1,
    totalPages: 1,
    isLoading: false,
    isRefreshing: false,
    hasMore: true,
    useMockData: false // 是否使用模拟数据，可设置为true进行测试
};

// DOM元素
const elements = {
    dataList: document.getElementById('dataList'),
    refreshTip: document.getElementById('refreshTip'),
    loadMore: document.getElementById('loadMore')
};

// 初始化
function init() {
    // 加载初始数据
    loadData(1, true);
    
    // 绑定下拉刷新事件
    bindPullRefresh();
    
    // 绑定上拉加载更多事件
    bindLoadMore();
}

// 加载数据
async function loadData(pageNum, isInit = false) {
    // 防止重复加载
    if (config.isLoading || (!config.hasMore && !isInit)) {
        return;
    }
    
    config.isLoading = true;
    
    if (isInit) {
        showSkeleton();
    } else {
        elements.loadMore.textContent = '加载中...';
    }
    
    try {
        let data;
        
        // 使用模拟数据或真实API
        if (config.useMockData) {
            console.log('使用模拟数据');
            data = getMockData(pageNum);
        } else {
            const response = await fetch(`${config.apiBase}?pageNum=${pageNum}&pageSize=${config.pageSize}`);
            
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            
            data = await response.json();
        }
        
        // 处理数据
        handleData(data, isInit);
        
    } catch (error) {
        console.error('数据加载失败:', error);
        // 显示错误信息，并提供模拟数据作为备选
        showError(`加载失败: ${error.message}，正在使用模拟数据`);
        
        // 使用模拟数据
        setTimeout(() => {
            const mockData = getMockData(pageNum);
            handleData(mockData, true);
            console.log('已切换到模拟数据');
        }, 1000);
    } finally {
        config.isLoading = false;
        hideSkeleton();
        elements.loadMore.textContent = config.hasMore ? '上拉加载更多...' : '没有更多数据了';
        if (config.hasMore) {
            elements.loadMore.classList.remove('no-more');
        } else {
            elements.loadMore.classList.add('no-more');
        }
    }
}

// 获取模拟数据 - 数据库信息格式
function getMockData(pageNum) {
    // 模拟用户提供的数据库信息数据
    const databaseData = {
        "total": 5,
        "rows": [
            {
                "createBy": "admin",
                "createTime": "2025-10-31 15:03:33",
                "updateBy": "",
                "updateTime": null,
                "remark": "测试数据库1",
                "databaseId": 1000,
                "databaseName": "MySQL",
                "icon": "https://example.com/icon/mysql.png",
                "dbType": "0",
                "deployType": "0",
                "description": "MySQL是一个开源的关系型数据库管理系统",
                "status": "0",
                "delFlag": "0"
            },
            {
                "createBy": "admin",
                "createTime": "2025-10-31 15:03:33",
                "updateBy": "",
                "updateTime": "2025-10-31 15:13:35",
                "remark": "测试数据库2",
                "databaseId": 1001,
                "databaseName": "MongoDB",
                "icon": "https://example.com/icon/mongodb.png",
                "dbType": "1",
                "deployType": "1",
                "description": "MongoDB是一个基于分布式文件存储的数据库",
                "status": "0",
                "delFlag": "0"
            },
            {
                "createBy": "admin",
                "createTime": "2025-10-31 15:03:33",
                "updateBy": "",
                "updateTime": "2025-10-31 15:13:02",
                "remark": "测试数据库3",
                "databaseId": 1002,
                "databaseName": "SQLite",
                "icon": "https://example.com/icon/sqlite.png",
                "dbType": "0",
                "deployType": "0",
                "description": "SQLite是一个轻量级的数据库，是一个进程内的库",
                "status": "0",
                "delFlag": "0"
            },
            {
                "createBy": "admin",
                "createTime": "2025-10-31 15:03:33",
                "updateBy": "",
                "updateTime": null,
                "remark": "测试数据库4",
                "databaseId": 1003,
                "databaseName": "Redis",
                "icon": "https://example.com/icon/redis.png",
                "dbType": "1",
                "deployType": "1",
                "description": "Redis是一个开源的使用ANSI C语言编写的键值对存储数据库",
                "status": "0",
                "delFlag": "0"
            },
            {
                "createBy": "",
                "createTime": "2025-10-31 15:16:19",
                "updateBy": "",
                "updateTime": null,
                "remark": null,
                "databaseId": 1004,
                "databaseName": "弱智数据库",
                "icon": "/profile/upload/2025/10/31/Default_20251031151600A001.jpg",
                "dbType": "0",
                "deployType": "1",
                "description": "6",
                "status": "0",
                "delFlag": "0"
            }
        ],
        "code": 200,
        "msg": "查询成功"
    };
    
    // 分页处理
    const pageSize = config.pageSize;
    const totalPages = Math.ceil(databaseData.total / pageSize);
    const startIndex = (pageNum - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, databaseData.rows.length);
    
    return {
        rows: databaseData.rows.slice(startIndex, endIndex),
        total: databaseData.total,
        code: databaseData.code,
        msg: databaseData.msg
    };
}

// 处理数据
function handleData(data, isInit) {
    // 灵活解析各种可能的API返回格式
    let list = [];
    let total = 0;
    let pages = 1;
    
    // 尝试多种可能的数据结构
    if (Array.isArray(data)) {
        // 直接返回数组
        list = data;
        total = data.length;
        pages = Math.ceil(total / config.pageSize);
    } else if (data.rows) {
        // 标准分页格式 { rows: [], total: number, pages: number }
        list = data.rows;
        total = data.total || 0;
        pages = data.pages || Math.ceil(total / config.pageSize) || 1;
    } else if (data.list || data.data || data.items) {
        // 其他常见格式
        list = data.list || data.data || data.items || [];
        total = data.total || list.length;
        pages = data.pages || Math.ceil(total / config.pageSize) || 1;
    }
    
    config.totalPages = pages;
    config.hasMore = config.currentPage < pages;
    
    // 清空列表（初始化或刷新时）
    if (isInit) {
        elements.dataList.innerHTML = '';
    }
    
    // 没有数据时显示提示
    if (list.length === 0 && isInit) {
        elements.dataList.innerHTML = '<li class="loading">暂无数据</li>';
        return;
    }
    
    // 添加数据项 - 数据库信息展示
    list.forEach(item => {
        const li = document.createElement('li');
        li.className = 'data-item';
        
        // 获取数据库信息
        const databaseName = item.databaseName || '未知数据库';
        const description = item.description || '暂无描述';
        const createTime = item.createTime || '未知时间';
        const remark = item.remark || '';
        const icon = item.icon || '';
        const dbType = item.dbType === '0' ? '关系型' : '非关系型';
        const deployType = item.deployType === '0' ? '单机部署' : '集群部署';
        
        // 处理图标URL（移除可能的空格和反引号）
        let iconUrl = icon ? icon.replace(/[` ]/g, '') : '';
        
        // 构建HTML内容
        const html = `
            <div class="database-header">
                ${iconUrl ? `<img src="${iconUrl}" alt="${databaseName}" onerror="handleImageError(this)" class="database-icon">` : '<div class="database-icon-placeholder">📊</div>'}
                <div class="database-title-area">
                    <h3>${escapeHtml(databaseName)}</h3>
                    <div class="database-meta">
                        <span class="meta-item">类型: ${dbType}</span>
                        <span class="meta-item">部署: ${deployType}</span>
                    </div>
                </div>
            </div>
            <p class="database-description">${escapeHtml(description)}</p>
            <div class="database-info">
                <span class="info-item">创建时间: ${createTime}</span>
                ${remark ? `<span class="info-item">备注: ${escapeHtml(remark)}</span>` : ''}
            </div>
        `;
        
        li.innerHTML = html;
        elements.dataList.appendChild(li);
    });
}

// HTML转义函数，防止XSS攻击
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 显示骨架屏
function showSkeleton() {
    elements.dataList.innerHTML = '';
    
    // 创建3个骨架屏项
    for (let i = 0; i < 3; i++) {
        const skeleton = document.createElement('li');
        skeleton.className = 'data-item';
        
        skeleton.innerHTML = `
            <div class="skeleton skeleton-img"></div>
            <div class="skeleton skeleton-title"></div>
            <div class="skeleton skeleton-desc"></div>
            <div class="skeleton skeleton-desc"></div>
        `;
        
        elements.dataList.appendChild(skeleton);
    }
}

// 隐藏骨架屏
function hideSkeleton() {
    const skeletons = elements.dataList.querySelectorAll('.skeleton');
    skeletons.forEach(skeleton => {
        skeleton.remove();
    });
}

// 显示错误信息
function showError(message) {
    elements.dataList.innerHTML = `<li class="loading">${message}</li>`;
}

// 绑定下拉刷新事件
function bindPullRefresh() {
    let startY = 0;
    let currentY = 0;
    let isPulling = false;
    let isAtTop = false;
    const REFRESH_THRESHOLD = 60; // 触发刷新的阈值
    const MAX_PULL_DISTANCE = 100; // 最大下拉距离
    
    // 监听滚动事件，判断是否在顶部
    window.addEventListener('scroll', () => {
        isAtTop = window.scrollY <= 10;
    });
    
    // 触摸开始
    elements.mainContent = document.querySelector('.main-content');
    elements.mainContent.addEventListener('touchstart', (e) => {
        // 只有在顶部才能下拉刷新
        if (isAtTop && !config.isRefreshing && !config.isLoading) {
            startY = e.touches[0].clientY;
            isPulling = true;
        }
    }, { passive: true });
    
    // 触摸移动
    elements.mainContent.addEventListener('touchmove', (e) => {
        if (!isPulling) return;
        
        currentY = e.touches[0].clientY;
        let pullDistance = currentY - startY;
        
        // 只处理下拉
        if (pullDistance <= 0) {
            elements.refreshTip.style.height = '0';
            elements.refreshTip.classList.remove('active');
            return;
        }
        
        // 限制最大下拉距离并添加阻力效果
        if (pullDistance > MAX_PULL_DISTANCE) {
            pullDistance = MAX_PULL_DISTANCE + (pullDistance - MAX_PULL_DISTANCE) * 0.3;
        }
        
        elements.refreshTip.style.height = `${pullDistance}px`;
        elements.refreshTip.classList.add('active');
        
        // 更新提示文本和样式
        if (pullDistance > REFRESH_THRESHOLD) {
            elements.refreshTip.textContent = '释放刷新...';
            elements.refreshTip.style.color = '#1890ff';
        } else {
            elements.refreshTip.textContent = '下拉刷新...';
            elements.refreshTip.style.color = '#999';
        }
        
        // 添加列表的位移效果
        elements.dataList.style.transform = `translateY(${pullDistance * 0.8}px)`;
        elements.dataList.style.transition = 'transform 0s';
    }, { passive: true });
    
    // 触摸结束
    elements.mainContent.addEventListener('touchend', () => {
        if (!isPulling) return;
        
        const pullDistance = currentY - startY;
        
        // 重置列表位移
        elements.dataList.style.transition = 'transform 0.3s ease';
        elements.dataList.style.transform = 'translateY(0)';
        
        if (pullDistance > REFRESH_THRESHOLD && !config.isRefreshing) {
            // 触发刷新
            refreshData();
        } else {
            // 恢复原位，添加动画
            elements.refreshTip.style.transition = 'height 0.3s ease';
            elements.refreshTip.style.height = '0';
            setTimeout(() => {
                elements.refreshTip.classList.remove('active');
                elements.refreshTip.style.color = '#999';
                elements.refreshTip.style.transition = 'none';
            }, 300);
        }
        
        isPulling = false;
    });
}

// 刷新数据
function refreshData() {
    config.isRefreshing = true;
    config.currentPage = 1;
    config.hasMore = true;
    
    // 更新刷新提示
    elements.refreshTip.textContent = '刷新中...';
    elements.refreshTip.style.color = '#1890ff';
    
    // 显示加载动画（可以添加旋转图标）
    const originalContent = elements.refreshTip.innerHTML;
    elements.refreshTip.innerHTML = '<span class="refresh-icon">🔄</span> 刷新中...';
    elements.refreshTip.querySelector('.refresh-icon').style.display = 'inline-block';
    elements.refreshTip.querySelector('.refresh-icon').style.animation = 'rotate 1s linear infinite';
    
    loadData(1, true).then(() => {
        // 显示刷新成功提示
        elements.refreshTip.textContent = '刷新成功';
        elements.refreshTip.style.color = '#52c41a';
        
        // 延迟恢复原位，让用户看到成功提示
        setTimeout(() => {
            elements.refreshTip.style.transition = 'height 0.3s ease';
            elements.refreshTip.style.height = '0';
            setTimeout(() => {
                elements.refreshTip.classList.remove('active');
                elements.refreshTip.innerHTML = '下拉刷新...';
                elements.refreshTip.style.color = '#999';
                elements.refreshTip.style.transition = 'none';
                config.isRefreshing = false;
            }, 300);
        }, 500);
    }).catch(() => {
        // 刷新失败时的处理
        elements.refreshTip.textContent = '刷新失败，下拉重试';
        elements.refreshTip.style.color = '#ff4d4f';
        setTimeout(() => {
            config.isRefreshing = false;
        }, 1000);
    });
}

// 绑定上拉加载更多事件
function bindLoadMore() {
    let lastScrollTop = 0;
    const LOAD_THRESHOLD = 150; // 距离底部多少像素时触发加载
    let isThrottling = false;
    const THROTTLE_DELAY = 200; // 节流延迟
    
    window.addEventListener('scroll', () => {
        // 节流处理，避免频繁触发
        if (isThrottling) return;
        
        // 只有向下滚动且满足条件时才触发
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (scrollTop <= lastScrollTop) {
            lastScrollTop = scrollTop;
            return;
        }
        
        lastScrollTop = scrollTop;
        
        // 检查是否正在加载、刷新或没有更多数据
        if (config.isLoading || config.isRefreshing || !config.hasMore) {
            isThrottling = true;
            setTimeout(() => {
                isThrottling = false;
            }, THROTTLE_DELAY);
            return;
        }
        
        // 获取滚动信息
        const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        const clientHeight = document.documentElement.clientHeight || window.innerHeight;
        const scrollBottom = scrollHeight - scrollTop - clientHeight;
        
        // 当滚动到底部附近时加载更多
        if (scrollBottom <= LOAD_THRESHOLD) {
            loadMore();
        }
        
        isThrottling = true;
        setTimeout(() => {
            isThrottling = false;
        }, THROTTLE_DELAY);
    });
}

// 加载更多
function loadMore() {
    if (config.currentPage < config.totalPages) {
        // 显示加载动画
        showLoadingAnimation();
        
        config.currentPage++;
        
        // 加载数据
        loadData(config.currentPage).then(() => {
            hideLoadingAnimation();
        }).catch(() => {
            // 加载失败时回滚页码
            config.currentPage--;
            hideLoadingAnimation();
            elements.loadMore.textContent = '加载失败，上拉重试';
            elements.loadMore.style.color = '#ff4d4f';
            
            // 3秒后恢复提示文本
            setTimeout(() => {
                elements.loadMore.textContent = config.hasMore ? '上拉加载更多...' : '没有更多数据了';
                elements.loadMore.style.color = '';
            }, 3000);
        });
    }
}

// 显示加载动画
function showLoadingAnimation() {
    // 保存原始内容以便恢复
    if (!config.originalLoadMoreContent) {
        config.originalLoadMoreContent = elements.loadMore.innerHTML;
    }
    
    // 添加加载动画
    elements.loadMore.innerHTML = '<span class="loading-icon">🔄</span> 加载中...';
    const icon = elements.loadMore.querySelector('.loading-icon');
    icon.style.display = 'inline-block';
    icon.style.animation = 'rotate 1s linear infinite';
    icon.style.marginRight = '5px';
}

// 隐藏加载动画
function hideLoadingAnimation() {
    if (config.originalLoadMoreContent) {
        elements.loadMore.innerHTML = config.originalLoadMoreContent;
    }
}

// 图片加载失败处理
function handleImageError(img) {
    img.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="200" viewBox="0 0 100 100" preserveAspectRatio="none"><rect width="100%" height="100%" fill="%23f0f0f0"/><text x="50%" y="50%" font-size="14" text-anchor="middle" dominant-baseline="middle" fill="%23999">图片加载失败</text></svg>';
}

// 导出全局函数用于图片错误处理
window.handleImageError = handleImageError;

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}